package com.wgj.android.ui.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jiaai.xui.XUI;
import com.jiaai.xui.adapter.XRecyclerViewAdapter;
import com.jiaai.xui.utils.XBitmapUtils;
import com.jiaai.xui.utils.XEmptyUtils;
import com.jiaai.xui.utils.http.HttpCallBack;
import com.jiaai.xui.utils.http.ListHttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.jiaai.xui.utils.log.XLog;
import com.jiaai.xui.utils.share.ShareUtils;
import com.jiaai.xui.utils.share.entity.Share;
import com.jiaai.xui.view.widget.XLoadingDialog;
import com.jiaai.xui.view.widget.XToast;
import com.jiaai.xui.view.widget.XTopbarView;
import com.wgj.android.R;
import com.wgj.android.adapter.TVCommentAdapter;
import com.wgj.android.dialog.ShareDiadlog;
import com.wgj.android.entity.SystemConfg;
import com.wgj.android.entity.TVComment;
import com.wgj.android.entity.Video;
import com.wgj.android.entity.YoukuBean;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.utils.CacheUtils;
import com.youku.cloud.module.PlayerErrorInfo;
import com.youku.cloud.player.PlayerListener;
import com.youku.cloud.player.VideoDefinition;
import com.youku.cloud.player.YoukuPlayerView;
import com.youku.cloud.player.YoukuUIListener;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class VideoTuiGuangActivity extends AppCompatActivity implements ShareDiadlog.OnShareListener {
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_introduce)
    TextView tvIntroduce;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.et_input_container)
    EditText etInputContainer;
    @BindView(R.id.topBar)
    XTopbarView topBar;
    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.iv_hui)
    ImageView ivHui;
    @BindView(R.id.iv_down)
    ImageView ivDown;
    @BindView(R.id.baseview)
    YoukuPlayerView youkuPlayerView;
    @BindView(R.id.llayout)
    LinearLayout llayout;
    @BindView(R.id.tv_share)
    TextView tvShare;
    private TVCommentAdapter adapter;
    private List<TVComment> TVComments = new ArrayList<>();
    private String video;
    private String video1;
    private Video videoBean;
    private int feedId = 0;

    private ShareDiadlog shareDiadlog;
    private SystemConfg confg;
    private Share share;
    private YoukuBean youkuBean;
    private String vid;
    private String password;
    private boolean local = false;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            tvShare.setClickable(true);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_tui_guang);
        ButterKnife.bind(this);
        video = getIntent().getStringExtra("video");
        //video1 = getIntent().getStringExtra("video1");
        // Log.i("tianyun", video);
        videoBean = new Gson().fromJson(video, Video.class);
        vid = videoBean.getResourceId();

        initView();
        //getVideo();
    }
    private void initView() {
        // 初始化播放器
        youkuPlayerView.attachActivity(this);
        youkuPlayerView.setPreferVideoDefinition(VideoDefinition.VIDEO_HD);
        youkuPlayerView.setShowBackBtn(true);
        youkuPlayerView.setPlayerListener(new MyPlayerListener());
        youkuPlayerView.setUIListener(new YoukuUIListener() {
            @Override
            public void onBackBtnClick() {
               finish();
            }

            @Override
            public void onFullBtnClick() {
                llayout.setVisibility(View.GONE);
                youkuPlayerView.goFullScreen();
            }
        });
        Log.e("liyh", "play");
        youkuPlayerView.setShowFullBtn(true);

        autoplayvideo();


        confg = CacheUtils.getSystemConfig();
        share = new Share();
        tvShare.setClickable(false);
        //share.setThumBitmap(XBitmapUtils.getBitmapFromDrawable(XUI.getDrawable(R.mipmap.icon_share)));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    share.setThumBitmap(getBitmap(videoBean.getThumbnail()));
                } catch (IOException e) {
                    e.printStackTrace();
                    share.setThumBitmap(XBitmapUtils.getBitmapFromDrawable(XUI.getDrawable(R.mipmap.logo)));
                }finally {
                   handler.sendEmptyMessage(0);
                }
            }
        }).start();
        share.setTitle(confg.getSharetitle());
        share.setWebUrl(videoBean.getAddressHttp());
        share.setDescription(confg.getSharecontent());
        shareDiadlog = new ShareDiadlog().setOnShareListener(this);

        tvContent.setText(videoBean.getIntroduce());
        adapter = new TVCommentAdapter(recyclerView, TVComments);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.setAdapter(adapter);
        //"http://jzvd.nathen.cn/6ea7357bc3fa4658b29b7933ba575008/fbbba953374248eb913cb1408dc61d85-5287d2089db37e62345123a1be272f8b.mp4"
        //videoPlayer.setUp(videoBean.getAddressHttp(), JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, videoBean.getTitle());
       /* videoPlayer.setUp(youkuBean.getLink(), JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, videoBean.getTitle());
        Glide.with(this).load(youkuBean.getThumbnail()).into(videoPlayer.thumbImageView);*/
        getData();
        adapter.setOnItemClickListener(new XRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int i) {
                //etInputContainer
                etInputContainer.setFocusable(true);
                etInputContainer.setFocusableInTouchMode(true);
                etInputContainer.requestFocus();

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(etInputContainer, 0);
                etInputContainer.setHint("回复: " + TVComments.get(i).getM_nick() + " " + TVComments.get(i).getMessage());
                feedId = TVComments.get(i).getId();
            }
        });

    }

    private void getData() {
        XLoadingDialog.with(this).show();
        XHttp.obtain().get(WGJAPI.SEACH_TV_MESSAGE + "?id=" + videoBean.getId(), null, new ListHttpCallBack<TVComment>() {


            @Override
            public void onSuccess(List<TVComment> list) {
                if (list.size() > 0) {
                    recyclerView.setVisibility(View.VISIBLE);
                    tvEmpty.setVisibility(View.GONE);
                }
                TVComments.clear();
                TVComments.addAll(list);
                adapter.notifyDataSetChanged();
                XLoadingDialog.with(VideoTuiGuangActivity.this).dismiss();
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                tvEmpty.setText("网络异常");
                XLog.e("网络异常");
                XLoadingDialog.with(VideoTuiGuangActivity.this).dismiss();
            }
        });
    }

    @OnClick(R.id.btn_send)
    public void send(View v) {
        if (ivDown.getVisibility() == View.VISIBLE) {
            tvIntroduce.performClick();
        }
        if (StringUtils.isEmpty(etInputContainer.getText())) {
            XToast.info("不能为空");
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("message", etInputContainer.getText());
        params.put("member", CacheUtils.getMember().getM_id());
        params.put("TvId", videoBean.getId());
        params.put("feedId", feedId);
       /* Comment comment =new Comment();
        comment.setMessage(etInputContainer.getText().toString());
        comment.setMember(CacheUtils.getMember().getM_id());
        comment.setTvId(videoBean.getId());
        comment.setFeedId(feedId);*/
        XHttp.obtain().post(WGJAPI.INSERT_TV_MESSAGE, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String str) {
                getData();
                XToast.success("评论成功");
                etInputContainer.setText("");
                tvContent.setVisibility(View.GONE);
                recyclerView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                XLog.e("网络异常");
            }
        });
    }

    @OnClick({R.id.tv_introduce, R.id.tv_share})
    public void onClic(View v) {
        //tvIntroduce.setD
        switch (v.getId()) {
            case R.id.tv_introduce:
                if (tvContent.getVisibility() == View.GONE) {
                    tvContent.setVisibility(View.VISIBLE);
                    ivDown.setVisibility(View.VISIBLE);
                    ivHui.setVisibility(View.INVISIBLE);
                    recyclerView.setVisibility(View.GONE);
                } else {
                    tvContent.setVisibility(View.GONE);
                    ivHui.setVisibility(View.VISIBLE);
                    ivDown.setVisibility(View.INVISIBLE);
                    recyclerView.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.tv_share:
                shareDiadlog.show(getSupportFragmentManager(), "shareDialog");
                break;
        }


    }

    @Override
    public void onShareWeiXin() {
        if (XEmptyUtils.isSpace(confg.getWXAppId())) {
            XToast.error("暂未开放");
        } else {
            ShareUtils.shareWeiXin(getApplication(), share, confg.getWXAppId(), false);
            shareDiadlog.dismiss();
        }
    }

    @Override
    public void onShareFriends() {
        if (XEmptyUtils.isSpace(confg.getWXAppId())) {
            XToast.error("暂未开放");
        } else {
            ShareUtils.shareWeiXin(getApplication(), share, confg.getWXAppId(), true);
            shareDiadlog.dismiss();
        }
    }

    @Override
    public void onShareSpaceBut() {
        XToast.error("暂未开放");
    }

    @Override
    public void onShareQQ() {
        XToast.error("暂未开放");
    }

    @Override
    public void onlinkButBut() {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText(null, videoBean.getAddressHttp()));
        XToast.success("分享接连已复制到粘贴板,可以发送给朋友们了.");
    }

    // 进入activity后自动播放，如不需要
    private void autoplayvideo() {
        if (local) {
            youkuPlayerView.playLocalVideo(vid);
        } else {
            if (TextUtils.isEmpty(password)) {
                youkuPlayerView.playYoukuVideo(vid);
            } else {
                youkuPlayerView.playYoukuPrivateVideo(vid, password);
            }
        }

    }

    @Override
    protected void onPause() {
        youkuPlayerView.onPause();
        Log.e("liyh", "player onPause");
        super.onPause();
        // 必须重写的onPause()

    }

    @Override
    protected void onResume() {
        youkuPlayerView.onResume();
        Log.e("liyh", "player onResume");
        super.onResume();
        // 必须重写的onResume()

    }

    @Override
    protected void onDestroy() {
        youkuPlayerView.onDestroy();
        Log.e("liyh", "player onDestroy");
        super.onDestroy();
        // 必须重写的onDestroy()

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Log.e("liyh", "onSaveInstanceState");
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        Log.e("liyh", "onSaveInstanceState2");
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        //后退键的处理，当全屏时，后退为变为小屏
        if (youkuPlayerView.isFullScreen()) {
            youkuPlayerView.goSmallScreen();
            llayout.setVisibility(View.VISIBLE);
        } else {
            super.onBackPressed();
        }
    }


    // 添加播放器的监听器
    private class MyPlayerListener extends PlayerListener {
        @Override
        public void onComplete() {
            // TODO Auto-generated method stub
            super.onComplete();
        }

        @Override
        public void onError(int code, PlayerErrorInfo info) {
            // TODO Auto-generated method stub
            // txt1.setText(info.getDesc());
            XToast.info(info.getDesc(), 1500);
        }

        @Override
        public void OnCurrentPositionChanged(int msec) {
            // TODO Auto-generated method stub
            super.OnCurrentPositionChanged(msec);
        }

        @Override
        public void onVideoNeedPassword(int code) {
            // TODO Auto-generated method stub
            super.onVideoNeedPassword(code);
        }

        @Override
        public void onVideoSizeChanged(int width, int height) {
            // TODO Auto-generated method stub
            super.onVideoSizeChanged(width, height);
        }

    }

    //根据图片的URL路径来获取网络图片，核心代码如下：
    public Bitmap getBitmap(String path) throws IOException {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");

        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

            return Bitmap.createScaledBitmap(bitmap, 100, 100, true);

        }
        return null;
    }
}
